package com.zggk.framework.controller.fileupload;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.platform.common.utils.StringUtils;
import com.platform.framework.controller.BaseController;
import com.platform.framework.entity.file.BaseFileEntity;
import com.platform.framework.service.file.CataLogueService;
import com.platform.framework.service.rights.FwRightUserService;
import com.zggk.framework.dao.file.BaseFileEntityRepository;
import com.zggk.framework.service.file.BaseFileEntityService;
import com.zggk.framework.utils.FileUtils;
import com.zggk.framework.utils.ReturnMessage;
import com.zggk.framework.utils.ThumbnailatorUtils;

import io.minio.MinioClient;

@RestController
public class FileUploadTaskController extends BaseController {

	@Autowired
	CataLogueService cataLogueService;
	@Autowired
	BaseFileEntityService baseFileEntityService;
	@Autowired
	FwRightUserService fwRightUserService;
	
	@Autowired
	BaseFileEntityRepository baseFileEntityRepository;
	

	/**
	 * 一般的文件上传页面
	 * 
	 * @return
	 */
	@RequestMapping("/commonUploadTask")
	public ModelAndView commonFileUpload(Model model) {
		ModelAndView mv = new ModelAndView("fileUpoload/commonIndexTask");
		return mv;
	}
	
	/**
	 * 
	 * user分页数据
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "getfileforlayui", method = { RequestMethod.POST })
	public String roleList(HttpServletRequest request) throws Exception {
		Object fileId = fwRightUserService.getDao().findBySql("select post_id from basic.fw_right_user where user_code = ?" ,new Object[] {this.getUserCode()}).get(0);
		if(StringUtils.isNotNull(StringUtils.toString(fileId))) {
			return StringUtils.toString(fileId);
		}
		return "";
	}
	
	  @RequestMapping(value={"/downloadforlayui"}, produces={"text/html;charset=UTF-8"})
	  @ResponseBody
	  public void download(HttpServletRequest request, HttpServletResponse response){
		    response.setCharacterEncoding("UTF-8");
	        String id = request.getParameter("id");
	        Object fileId = "";
			try {
				fileId = fwRightUserService.getDao().findBySql("select post_id from basic.fw_right_user where user_code = '"+this.getUserCode()+"'").get(0);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(StringUtils.isNotNull(StringUtils.toString(fileId))) {
				id = StringUtils.toString(fileId);
			}else {
				id = "de1758a0cbad47398c3e016ce556d989";//给一个默认值的图片
			}
	        baseFileEntityService.downLoadById(id,response);
	  }
	
	/**
	 * 
	 * @Description 普通文件上传操作
	 * @author 王求卿
	 * @param file
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/uploadforlayui")
	public String uploadLayUIFile(@RequestParam("file") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException {
		ReturnMessage msg = new ReturnMessage();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		try {
			InputStream fileInput = file.getInputStream();
			ByteArrayOutputStream fileOut = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int len;
			while ((len = fileInput.read(b)) > -1) {
				fileOut.write(b, 0, len);
			}
			fileOut.flush();
			// 获得文件名
			String fileName = file.getOriginalFilename();
			String path = "我的文档";
			// 获取文件后缀名并转化为小写，用于后续比较
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
			if(!"jpg,png,jpeg,bmp".contains(fileType)) {
				msg.setStatus("false");
				msg.setData("非法的格式");
				msg.setInfo("非法的格式");
				return JSONObject.toJSONString(msg);
			}
			
			InputStream thumbsImg = null;
			String md5 = DigestUtils.md5Hex(file.getInputStream());

			String bucket = "lwzx";
			String objectName = "";
			boolean isSendTask = true;
			BaseFileEntity existBaseFileEntity = baseFileEntityService.isExistFile(md5);
			if (existBaseFileEntity == null) {
				MinioClient minioClient = FileUtils.getInstance();
				boolean isExist = minioClient.bucketExists(bucket);
				if (isExist) {
					System.out.println("Bucket already exists.");
				} else {
					// Make a new bucket called asiatrip to hold a zip file of photos.
					minioClient.makeBucket(bucket);
				}
				// Upload file to the bucket with putObject
				System.out.println("文件长度：" + file.getSize());
				String newFileName = getUUID() + "." + fileType;
				// 上传文件,如果是图片类型,处理缩略图上传到"我的图片/thumbs"
				if (FileUtils.isImage(fileType)) {
					path = "我的图片";
					InputStream thumInput = new BufferedInputStream(new ByteArrayInputStream(fileOut.toByteArray()));
					thumbsImg = ThumbnailatorUtils.getThumbsImg(thumInput);// 获取缩略图流
					thumInput.close();
					// 创建目录thumbs
					objectName = path + "/" + this.getUserCode() + "/thumbs/" + newFileName;
					minioClient.putObject(bucket, objectName, thumbsImg, thumbsImg.available(),
							"application/octet-stream");
					thumbsImg.close();
					isSendTask = false;
				}
				InputStream orgInput = new BufferedInputStream(new ByteArrayInputStream(fileOut.toByteArray()));

				objectName = path + "/" + this.getUserCode() + "/" + newFileName;
				minioClient.putObject(bucket, objectName, orgInput, orgInput.available(), "application/octet-stream");
				fileInput.close();
				BaseFileEntity baseFileEntity = new BaseFileEntity();
				baseFileEntity.setId(getUUID());
				baseFileEntity.setFileName(fileName);
				baseFileEntity.setFileNewName(newFileName);
				baseFileEntity.setFileDirectory("lwzx");
				baseFileEntity.setFilePath(path + "/" + this.getUserCode() + "/");
				baseFileEntity.setAbsolutePath(
						minioClient.getObjectUrl("lwzx", path + "/" + this.getUserCode() + "/" + newFileName));
				baseFileEntity.setFileSize(file.getSize());
				baseFileEntity.setFileType(fileType);
				baseFileEntity.setFileMd5(md5);
				baseFileEntity.setCreateUserCode(this.getUserCode());
				baseFileEntity.setCreateUserName(this.getUserEntity().getName());
				baseFileEntity.setCreateTime(new Date());
				baseFileEntity.setUpdateUserCode(this.getUserCode());
				baseFileEntity.setUpdateUserName(this.getUserEntity().getName());
				baseFileEntityService.saveFileInfo(baseFileEntity);
				
				msg.setData(baseFileEntity.getId());
				
				baseFileEntityRepository.updatepostid(baseFileEntity.getId(), this.getUserCode());
				
			} else {
				objectName = path + "/" + this.getUserCode() + "/" + existBaseFileEntity.getFileNewName();
				existBaseFileEntity.setFileName(fileName);
				baseFileEntityService.saveFileInfo(existBaseFileEntity);
				msg.setData(existBaseFileEntity.getId());
				
				baseFileEntityRepository.updatepostid(existBaseFileEntity.getId(), this.getUserCode());
			}
			msg.setStatus("true");
			msg.setInfo(file.getOriginalFilename() + "上传成功");
			
			
			
			
			//fwRightUserService.getDao().saveOrUpdateBySql("update basic.fw_right_user set post_id = ? where user_code = ?",new Object[] {msg.getData().toString(),this.getUserCode()});
			
			System.out.println(file.getOriginalFilename() + " is uploaded successfully");
		} catch (Exception e) {
			e.printStackTrace();
			msg.setStatus("false");
			msg.setData(e.toString());
		}
		return JSONObject.toJSONString(msg);
	}


	
}
